package org.example.watermark;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.WatermarkGenerator;
import org.apache.flink.api.common.eventtime.WatermarkGeneratorSupplier;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.example.data.WaterSensor;
import org.example.function.WaterSensorMapFunction;

import java.time.Duration;

public class WatermarkCustomDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //设置默认周期为200毫秒
        env.getConfig().setAutoWatermarkInterval(2000L);

        DataStreamSource<String> source = env.socketTextStream("localhost", 9999);
        SingleOutputStreamOperator<WaterSensor> sensorDS = source.map(new WaterSensorMapFunction());

        WatermarkStrategy<WaterSensor> waterSensorWatermarkStrategy = WatermarkStrategy
                //指定乱序的Watermark生成，3秒
                //.<WaterSensor>forGenerator(context -> new MyPeriodWatermarkGenerator<>(3000L))
                .<WaterSensor>forGenerator(context -> new MyPuntuatedWatermarkGenerator<>(3000L))
                .withTimestampAssigner((WaterSensor waterSensor, long l) -> {
                    //返回的时间戳 毫秒
                    String recordTime = DateFormatUtils.format(l, "yyyy-MM-dd HH:mm:ss.SSS");
                    System.out.println("数据element：" + waterSensor + "，当前时间：" + l + ",recordTime:" + recordTime);
                    return waterSensor.getTs() * 1000;
                });

        SingleOutputStreamOperator<WaterSensor> sensorDsWithWatermark = sensorDS.assignTimestampsAndWatermarks(waterSensorWatermarkStrategy);
        sensorDsWithWatermark.keyBy(WaterSensor::getId)
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, ProcessWindowFunction<WaterSensor, String, String, TimeWindow>.Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        long start = context.window().getStart();
                        String startDate = DateFormatUtils.format(start, "yyyy-MM-dd HH:mm:ss.SSS");
                        long end = context.window().getEnd();
                        String endDate = DateFormatUtils.format(end, "yyyy-MM-dd HH:mm:ss.SSS");
                        long l = elements.spliterator().estimateSize();
                        out.collect("key为：" + s + "的窗口[" + startDate + "," + endDate + ")中一共有" + l + "条数据,elements:" + elements.toString());
                    }
                }).print();

        env.execute("WatermarkMonoDemo");

    }
}
